﻿namespace Blaze.Editor.CLI
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;

    /// <summary>
    /// 版本状态信息。
    /// </summary>
    public struct StatusInfo
    {
        public struct Entry
        {
            public string Path;
            public VersionStatus Status;
        }

        public Entry[] Entries;

        /// <summary>
        /// 获取一个值，表示版本是否有修改。
        /// </summary>
        public bool IsModifed
        {
            get { return Entries != null && Entries.Any(e => e.Status == VersionStatus.Modified || e.Status == VersionStatus.Conflicted || e.Status == VersionStatus.Unversion); }
        }

        public static StatusInfo Parse(string result)
        {
            var query = from Match match in mRegex.Matches(result)
                let status = mStatus[match.Result("${status}")]
                let path = match.Result("${path}")
                select new Entry
                {
                    Path = path,
                    Status = status,
                };

            return new StatusInfo
            {
                Entries = query.ToArray(),
            };
        }

        private static readonly Regex mRegex = new Regex("(?<status>[MC\\?]) +(?<path>.+?)\\r\\n");

        private static readonly Dictionary<string, VersionStatus> mStatus = new Dictionary<string, VersionStatus>
        {
            {"M", VersionStatus.Modified},
            {"C", VersionStatus.Conflicted},
            {"?", VersionStatus.Unversion},
        };
    }
}